<template>
  <div class="dashboard-container">
    <div class="filter-container">
      <el-row :gutter="10" style="width:100%">
        <el-col :span="4">
          <el-input
            v-model="listQuery.username"
            placeholder="用户名称"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="4">
          <el-input
            v-model="listQuery.client_name"
            placeholder="客户名称"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="4">
          <el-input
            v-model="listQuery.name"
            placeholder="收件人"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="4">
          <el-input
            v-model="listQuery.nation"
            placeholder="国家"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="4">
          <el-select
            v-model="listQuery.is_default"
            style="width:100%"
            placeholder="是否默认"
            clearable
            @change="reloadList"
          >

            <el-option
              label="是"
              :value="1"
            />
            <el-option
              label="否"
              :value="2"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-date-picker
            v-model="listQuery.add_time"
            style="width: 100%;"
            type="datetimerange"
            range-separator="~"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="创建开始日期"
            end-placeholder="创建结束日期"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-col>
        <el-col :span="24">
          <div class="buttons">
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              style="margin-top:10px"
              @click="reloadList"
            >搜索</el-button>
            <!-- <el-button
              class="filter-item"
              style="margin-left: 10px;"
              icon="el-icon-edit"
              @click="addNews"
            >
              添加
            </el-button> -->
            <el-upload
              ref="upload"
              class="upload-demo"
              accept=".xls,.xlsx"
              action="https://localhost:8080/posts/"
              :on-change="upload"
              :show-file-list="false"
              :auto-upload="false"
            >
              <el-button
                slot="trigger"
                icon="el-icon-upload"
                type="primary"
              >导入地址</el-button>
            </el-upload>
            <el-button
              class="filter-item"
              type="warning"
              icon="el-icon-download"
              style="margin-left:10px"
              @click="downLoadModel"
            >下载模板</el-button>
          </div>

        </el-col>
      </el-row>
    </div>
    <div style="padding:0 20px">

      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        height="calc(100vh - 250px)"
        style="width: 100%;"
        size="mini"
        border
        tooltip-effect="dark"
        :header-cell-style="{ background: '#eaf1fd', color: '#333' }"
      >
        <el-table-column
          label="用户名称"
          prop="user.username"
          width="180"
        />
        <el-table-column
          label="客户名称"
          prop="client.username"
          width="180"
        />
        <el-table-column
          label="收件人"
          prop="name"
          width="150"
        />
        <el-table-column
          label="国家"
          prop="nation"
          width="150"
        />
        <el-table-column
          label="电话"
          prop="context"
          width="150"
        >
          <template slot-scope="{ row }">
            <div>
              <span style="margin-right:5px">+{{ row.area_code }}</span>
              <span>{{ row.mobile }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="地址"
          prop="context"
          min-width="350"
        >
          <template slot-scope="{ row }">
            <div>
              <span style="margin-right:5px">{{ row.nation }} {{ row.province }}{{ row.city }}{{ row.district }}{{ row.detailed }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="邮编"
          prop="postcode"
          width="150"
        />
        <el-table-column
          label="默认地址"
          prop="context"
          width="100"
        >
          <template slot-scope="{ row }">
            <div>
              <span v-if="row.is_default == 1" style="color:blue">是</span>
              <span v-else style="color:red">否</span>

            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="add_time"
          width="150"
        />
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <!-- <Detial :detial="detial" :status="status" :visible="visible" @update="closeDraw" @reload="reloadList" /> -->
    <el-dialog
      title="导入结果"
      :visible.sync="dialogUpLoad"
      width="500px"
      :before-close="handleClose"
    >
      <div style="padding:20px">
        <el-progress :percentage="((getNumBatchSucNum + getNumBatchErrNum) / selectList.length * 100).toFixed()" />

        <div style="font-size: 16px; margin-top: 15px;">
          共 {{ selectList.length }} 单，成功 {{ getNumBatchSucNum }} 单，失败 {{ getNumBatchErrNum }} 单
        </div>
        <!-- <div v-if="getNumBatchErrList.length > 0" style="font-size: 16px; margin-top: 15px;">
          <el-alert
            v-for="(item,index) in getNumBatchErrList"
            :key="index"
            :title="item.msg + ' X ' +item.user_mark"
            :closable="false"
            style="margin-top: 10px;"
            type="error"
            show-icon
          />
        </div> -->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogUpLoad = false;">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listClientAddress, importCustomerAddress } from '@/api/connection/index'
import { AddressCorrect } from '@/api/order/index'

import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// import Detial from './components/flightDetial.vue'
import xlsx from 'xlsx'
import { sheet2Data } from '@/utils/excel'
import _ from 'lodash'
export default {
  name: 'Dashboard',
  components: {
    Pagination
    // Detial
  },
  data() {
    return {
      data_arr: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        username: '',
        client_name: '',
        name: '',
        nation: '',
        add_time: []
      },
      visible: false,
      status: 1,
      id: '',
      detial: {},
      message: '',
      loadingExcel: null,
      dialogUpLoad: false,
      getNumBatchSucNum: 0,
      getNumBatchErrNum: 0,
      selectList: [],
      getNumBatchErrList: []
    }
  },
  computed: {
  },
  created() {
    this.getList()
  },
  methods: {
    downLoadModel() {
      window.location.href =
		'https://syd-pub.oss-cn-qingdao.aliyuncs.com/download/%E4%B8%80%E8%88%AC%E8%B4%B8%E6%98%93/%E4%B8%80%E8%88%AC%E8%B4%B8%E6%98%93%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E5%AE%A2%E6%88%B7-%E5%90%8E%E5%8F%B0.xlsx'
    },
    handleClose() {
      this.dialogUpLoad = false
    },
    closeDraw() {
      this.visible = false
    },
    addNews() {
      this.status = 1
      this.visible = true
    },
    edit(row) {
      this.detial = { ...row }
      this.status = 2
      this.visible = true
    },
    // delet(row) {
    //   this.$confirm('确认删除该航班, 是否继续?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(() => {
    //     delFlight({
    //       id: row.id
    //     }).then(res => {
    //       this.$message({
    //         type: 'success',
    //         message: '删除成功!'
    //       })
    //       this.getList()
    //     })
    //   }).catch(() => {

    //   })
    // },
    reloadList() {
      this.listQuery.page = 1
      this.visible = false
      this.getList()
    },
    getList() {
      this.listLoading = true
      listClientAddress(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    addressCorrect(address) {
      return new Promise((resolve, reject) => {
        if (address) {
          AddressCorrect({
            country: 'CN',
            address: address
          }).then((res) => {
            resolve({
              province: res.data.state,
              city: res.data.city,
              district: res.data.district,
              detailed: res.data.detail
            })
          })
        } else {
          resolve({
            province: '',
            city: '',
            district: '',
            detailed: ''
          })
        }
      })
    },
    upFile(list) {
      return new Promise((resolve, reject) => {
        importCustomerAddress({
          list: list
        }).then(res => {
          this.getNumBatchErrNum += res.data.length
          this.getNumBatchSucNum += (list.length - res.data.length)
          // this.getNumBatchErrList = this.getNumBatchErrList.concat(res.data)
          resolve(true)
        })
      })
    },
    upload(file, fileList) {
      this.loadingExcel = this.$loading({
        lock: true,
        text: '导入数据中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const files = { 0: file.raw }// 取到File
      this.readExcel(files)
    },
    async readExcel(files) { // 表格导入
      var that = this
      if (files.length <= 0) { // 如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$Message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }

      const fileReader = new FileReader()
      fileReader.onload = async(files) => {
        try {
          const data = files.target.result
          const workbook = xlsx.read(data, {
            type: 'binary'
          })
          const worksheet = workbook.Sheets[workbook.SheetNames[0]]
          // data = XLSX.utils.sheet_to_json(worksheet);
          const file = sheet2Data(worksheet, 'I')
          // const arr = [
          //   '用户名',
          //   '客户名称',
          //   '客户唛头',
          //   '客户代码',
          //   '姓名',
          //   '电话区号\n中国86\n韩国82\n日本81',
          //   '手机号',
          //   '邮编',
          //   '详细地址'
          // ]
          // if (!_.isEqual(arr, file[2])) {
          //   this.$message.error('上传模版错误')
          //   this.loadingExcel.close()
          //   return false
          // }

          // 重写数据
          const goodList = file.splice(3, file.length - 1)
          this.selectList = []
          this.getNumBatchErrList = []
          this.getNumBatchSucNum = 0
          this.getNumBatchErrNum = 0

          for (const index in goodList) {
            const item = goodList[index]
            const address = await this.addressCorrect(item[8])
            const obj = {
              username: item[0],
              client_username: item[1],
              user_mark: item[2],
              code: item[3],
              name: item[4],
              area_code: item[5],
              mobile: item[6],
              postcode: item[7],
              nation: '中国',
              province: address.province,
              city: address.city,
              district: address.district,
              detailed: address.detailed
            }
            this.selectList.push(obj)
          }
          this.loadingExcel.close()

          this.dialogUpLoad = true
          const chunkList = _.chunk(this.selectList, 10)
          for (let index = 0; index < chunkList.length; index++) {
            const element = chunkList[index]
            await that.upFile(element)
          }
          this.reloadList()
          this.$refs.upload.value = ''
          // return ws
        } catch (e) {
          // this.dialogUpLoad = false
          console.log(e)
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    }

  }

}
</script>
<style scoped lang="scss">
.filter-container{
  padding:20px 20px 10px;
}

.upload-demo{
  margin: 20px 0 10px;
}
.buttons{
  .upload-demo{
    margin: 0;
    display: inline-block;
    margin-left: 10px;
  }
}

</style>
